<template>
	<view>
		<!-- 自定义卡片轮播 -->
		<swiper class="swiperBox" :previous-margin="swiper.margin" :next-margin="swiper.margin" :circular="true"
			@change="swiperChange" :current="swiper.index">
			<swiper-item class="swiperItem" v-for="(item, index) in swiper.list" :key="index">
				<view class="swiperWrap" :class="{ 'active': swiper.index === index }"
					@click="handleAvatarClick(index)">
					<view class="swiperPic">
						<image :src="item.fullUrl"
							:class="{ 'active-img': swiper.index === index, 'inactive-img': swiper.index !== index }"
							mode="widthFix">
						</image>
						<!-- 只在选中的图片上显示相机图标 -->
						<view v-if="swiper.index === index" class="caream-box" @click.stop="showAvatarPopup">
							<image :src="`${ImgBaseUrl}camera.png`" mode="" class="caream"></image>
						</view>
					</view>
				</view>
			</swiper-item>
		</swiper>
		<!-- 头像修改弹窗 -->
		<uni-popup ref="AvatarPopupRef" background-color="#fff" type="bottom">
			<view class="avatar-popup-content">
				<view class="avatar-popup-options">
					<view class="avatar-popup-option" @click="chooseImage('camera')">拍照</view>
					<view class="avatar-popup-option" @click="chooseImage('album')">从相册选择</view>
					<view class="avatar-popup-option cancel" @click="closeAvatarPopup">取消</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed,
		watch
	} from 'vue'
	import {
		ImgBaseUrl
	} from '@/utils/domain.js'
	import {
		useStore
	} from 'vuex';
	import {
		qiNiuFileUpload
	} from '@/utils/qiniu.js';
	import {
		getAvatarList
	} from '@/api/user.js'

	const store = useStore();
	const AvatarPopupRef = ref(null)
	const tempAvatarPath = ref('')
	const userInfo = computed(() => store.state.userInfo || {});
	const emit = defineEmits(['avatar-change']);

	const swiper = reactive({
		margin: "210rpx",
		index: 0,
		list: [] // 初始化为空数组，等待接口数据填充
	})

	// 监听用户信息变化
	watch(userInfo, (newVal) => {
		if (newVal && newVal.avatar) {
			updateCustomAvatar(newVal.avatar);
		}
	}, {
		immediate: true,
		deep: true
	});

	// 更新自定义头像
	const updateCustomAvatar = (avatarUrl) => {
		// 检查是否已经是自定义头像，避免重复添加
		const hasCustom = swiper.list.some(item => item.isCustom);

		if (!hasCustom) {
			// 添加自定义头像项
			swiper.list.unshift({
				fullUrl: avatarUrl,
				baseUrl: avatarUrl, // 自定义头像的baseUrl和fullUrl相同
				isCustom: true
			});
			swiper.index = 0; // 切换到自定义头像
		} else {
			// 更新已有的自定义头像
			const customIndex = swiper.list.findIndex(item => item.isCustom);
			if (customIndex !== -1) {
				swiper.list[customIndex].fullUrl = avatarUrl;
				swiper.list[customIndex].baseUrl = avatarUrl;
				swiper.index = customIndex;
			}
		}

		// 通知父组件头像变更
		emit('avatar-change', {
			index: swiper.index,
			tempPath: avatarUrl,
			isCustom: true,
			baseUrl: avatarUrl
		});
	};

	// swiper滑动事件
	const swiperChange = (e) => {
		swiper.index = e.detail.current;
		const currentItem = swiper.list[swiper.index];
		emit('avatar-change', {
			index: swiper.index,
			tempPath: currentItem.fullUrl,
			baseUrl: currentItem.baseUrl,
			isCustom: currentItem.isCustom || false
		});
	};

	// 头像点击事件
	const handleAvatarClick = (index) => {
		swiper.index = index;
		const currentItem = swiper.list[index];
		emit('avatar-change', {
			index: index,
			tempPath: currentItem.fullUrl,
			baseUrl: currentItem.baseUrl,
			isCustom: currentItem.isCustom || false
		});
	};

	// 显示头像弹窗
	const showAvatarPopup = () => {
		AvatarPopupRef.value.open();
	}

	// 关闭头像弹窗
	const closeAvatarPopup = () => {
		AvatarPopupRef.value.close()
	}

	// 拍照或选择图片
	const chooseImage = (type) => {
		closeAvatarPopup();

		if (type === 'camera') {
			checkCameraPermission().then(() => {
				openCamera();
			}).catch(err => {
				console.log('相机权限检查失败:', err);
				uni.showToast({
					title: '无法访问相机',
					icon: 'none'
				});
			});
		} else {
			openAlbum();
		}
	};

	// 检查相机权限
	const checkCameraPermission = () => {
		return new Promise((resolve, reject) => {
			uni.authorize({
				scope: 'scope.camera',
				success: resolve,
				fail: (err) => {
					if (err.errMsg.includes('auth deny')) {
						uni.showModal({
							title: '提示',
							content: '需要相机权限才能拍照，是否去设置开启权限？',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting();
								}
							}
						});
					}
					reject(err);
				}
			});
		});
	};

	// 打开相机拍照
	const openCamera = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['camera'],
			camera: 'front',
			success: (res) => {
				handleImageSuccess(res.tempFilePaths[0]);
			},
			fail: (err) => {
				console.error('拍照失败:', err);
				uni.showToast({
					title: '拍照失败',
					icon: 'none'
				});
			}
		});
	};

	// 打开相册选择
	const openAlbum = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album'],
			success: (res) => {
				handleImageSuccess(res.tempFilePaths[0]);
			},
			fail: (err) => {
				console.error('选择图片失败:', err);
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				});
			}
		});
	};

	const handleImageSuccess = (tempFilePath) => {
		if (tempFilePath) {
			uni.showLoading({
				title: '处理中...',
				mask: true
			});
			tempAvatarPath.value = tempFilePath;

			compressImage(tempFilePath).then(compressedPath => {
				// 更新当前显示的头像（如果是自定义头像）
				if (swiper.list[swiper.index]?.isCustom) {
					swiper.list[swiper.index].fullUrl = compressedPath;
					swiper.list[swiper.index].baseUrl = compressedPath;
				} else {
					// 如果当前不是自定义头像，添加一个新的自定义头像项
					swiper.list.unshift({
						fullUrl: compressedPath,
						baseUrl: compressedPath,
						isCustom: true
					});
					swiper.index = 0;
				}

				emit('avatar-change', {
					index: swiper.index,
					tempPath: compressedPath,
					baseUrl: compressedPath,
					isCustom: true
				});

				uni.hideLoading();
			}).catch(err => {
				console.log('压缩失败，使用原图', err);
				const originalPath = tempFilePath;

				if (swiper.list[swiper.index]?.isCustom) {
					swiper.list[swiper.index].fullUrl = originalPath;
					swiper.list[swiper.index].baseUrl = originalPath;
				} else {
					swiper.list.unshift({
						fullUrl: originalPath,
						baseUrl: originalPath,
						isCustom: true
					});
					swiper.index = 0;
				}

				emit('avatar-change', {
					index: swiper.index,
					tempPath: originalPath,
					baseUrl: originalPath,
					isCustom: true
				});

				uni.hideLoading();
			});
		}
	};

	// 暴露上传方法给父组件
	const uploadAvatar = async () => {
		if (!tempAvatarPath.value && !swiper.list[swiper.index]?.isCustom) {
			throw new Error('请先选择头像');
		}

		try {
			uni.showLoading({
				title: '上传中...',
				mask: true
			});

			// 如果是自定义头像且已选择新图片，则上传新图片
			if (tempAvatarPath.value) {
				const avatarUrl = await uploadAvatarToQiNiu();
				// 更新本地存储和Vuex
				await updateUserAvatar(avatarUrl);
				return avatarUrl;
			}
			// 如果已经是自定义头像但没有选择新图片，直接返回当前头像URL
			else if (swiper.list[swiper.index]?.isCustom) {
				return swiper.list[swiper.index].baseUrl;
			}
			// 如果是默认头像，返回baseUrl
			else {
				return swiper.list[swiper.index].baseUrl;
			}
		} catch (error) {
			console.error('上传失败:', error);
			throw error;
		} finally {
			uni.hideLoading();
		}
	};

	// 更新用户头像到服务器和本地存储
	const updateUserAvatar = async (avatarUrl) => {
		try {
			const userInfo = store.state.userInfo || {};
			const updatedUserInfo = {
				...userInfo,
				avatar: avatarUrl
			};

			store.commit('setUserInfo', updatedUserInfo);
			uni.setStorageSync('user_info', JSON.stringify(updatedUserInfo));

			return avatarUrl;
		} catch (error) {
			console.error('更新用户头像失败:', error);
			throw error;
		}
	};

	const setCurrentIndex = (index) => {
		swiper.index = index;
	};

	// 图片压缩
	const compressImage = (src) => {
		return new Promise((resolve, reject) => {
			uni.compressImage({
				src,
				quality: 70,
				success: (res) => {
					resolve(res.tempFilePath);
				},
				fail: reject
			});
		});
	};

	// 上传头像到七牛云
	const uploadAvatarToQiNiu = async () => {
		const userId = userInfo.value.id || 'defaultUserId';
		const timestamp = Date.now();
		const random = Math.floor(Math.random() * 10);
		const key = `images/avatar/${userId}/${timestamp}_${random}.png`;

		return new Promise((resolve, reject) => {
			qiNiuFileUpload(
				[{
					path: tempAvatarPath.value,
					key
				}],
				(successUrl) => {
					resolve(key);
				},
				(error) => {
					reject(error);
				}
			);
		});
	};

	defineExpose({
		uploadAvatar,
		setCurrentIndex,
		updateCustomAvatar,
		swiper
	});

	// 获取默认头像列表
	const getAvatarListApi = async () => {
		try {
			const res = await getAvatarList();
			if (res.code === 200 && res.data) {
				// 将接口返回的数据映射为组件需要的格式
				const avatarList = res.data.map(item => ({
					fullUrl: item.fullUrl,
					baseUrl: item.baseUrl,
					isCustom: false
				}));

				// 保留原有的自定义头像（如果有）
				const customAvatar = swiper.list.find(item => item.isCustom);
				if (customAvatar) {
					avatarList.unshift(customAvatar);
				}

				swiper.list = avatarList;
			}
		} catch (error) {
			console.error('获取默认头像失败:', error);
			// 使用本地默认头像作为后备
			swiper.list = [{
					fullUrl: `${ImgBaseUrl}avatar1.png`,
					baseUrl: 'images/avatar/default/avatar1.png',
					isCustom: false
				},
				{
					fullUrl: `${ImgBaseUrl}avatar2.png`,
					baseUrl: 'images/avatar/default/avatar2.png',
					isCustom: false
				},
				{
					fullUrl: `${ImgBaseUrl}avatar3.png`,
					baseUrl: 'images/avatar/default/avatar3.png',
					isCustom: false
				},
				{
					fullUrl: `${ImgBaseUrl}avatar4.png`,
					baseUrl: 'images/avatar/default/avatar4.png',
					isCustom: false
				},
				{
					fullUrl: `${ImgBaseUrl}avatar5.png`,
					baseUrl: 'images/avatar/default/avatar5.png',
					isCustom: false
				},
				{
					fullUrl: `${ImgBaseUrl}avatar6.png`,
					baseUrl: 'images/avatar/default/avatar6.png',
					isCustom: false
				}
			];
		}
	};

	onMounted(() => {
		getAvatarListApi();

		const userInfo = uni.getStorageSync('user_info');
		if (userInfo) {
			try {
				const parsedUserInfo = JSON.parse(userInfo);
				if (parsedUserInfo.avatar) {
					updateCustomAvatar(parsedUserInfo.avatar);
				}
			} catch (e) {
				console.error('解析用户信息失败:', e);
			}
		}
	});
</script>

<style scoped lang="scss">
	/* 样式保持不变 */
	.swiperBox {
		height: 260rpx;
		overflow: hidden;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.swiperItem {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.swiperWrap {
		transition: all 0.3s ease-in-out 0s;
		padding: 20rpx;
	}

	.swiperPic {
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;
	}

	.caream-box {
		width: 42rpx;
		height: 42rpx;
		background: #2F80ED;
		border: 2rpx solid #FFFFFF;
		position: absolute;
		right: 0rpx;
		bottom: 0rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;

		.caream {
			width: 22rpx;
			height: 20rpx;
		}
	}

	.active-img {
		width: 180rpx;
		height: 180rpx;
		border: 2rpx solid #fff;
		transition: all 0.3s ease-in-out 0s;
		border-radius: 50%;
	}

	.inactive-img {
		width: 96rpx;
		height: 96rpx;
		opacity: 0.7;
		transition: all 0.3s ease-in-out 0s;
	}

	.avatar-popup-content {
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		height: 360rpx;

		.avatar-popup-options {
			background-color: #fff;
			border-radius: 24rpx 24rpx 0 0;
			overflow: hidden;
			height: 100%;

			.avatar-popup-option {
				padding: 30rpx 0;
				text-align: center;
				font-size: 32rpx;
				color: #333;
				border-bottom: 1rpx solid #f0f0f0;

				&:active {
					background-color: #f9f9f9;
				}

				&.cancel {
					margin-top: 20rpx;
					border-radius: 0 0 24rpx 24rpx;
					border-bottom: none;
					color: #ff3b30;
					background-color: #fff;
				}
			}
		}
	}
</style>